<template>
  <CloudDialog
    v-model:visible="visible"
    :loading="loading"
    title="上传节点包"
    :width="480"
    :mask-closable="false"
    :cancel="handleClose"
    :footer="false">
    <!-- <template #footer>
      <a-button @click="handleClose">关闭</a-button>
    </template> -->
    <a-spin :loading="loading" class="w-full">
      <a-form ref="formRef" layout="vertical" :model="formState">
        <a-form-item label="" asterisk-position="end">
          <template #label>
            <div class="flex flex-col">
              <span>节点包</span>
              <span class="text-5 text-xs leading-5">
                仅支持文件格式：.tar.gz</span
              >
            </div>
          </template>
          <div class="w-full">
            <div>
              <a-upload
                ref="upload"
                v-model:file-list="fileList"
                class="flex-1"
                :multiple="false"
                :before-upload="beforeUpload"
                :custom-request="customRequest"
                :on-before-upload="
                  () => {
                    fileList = []
                    return true
                  }
                "
                accept="application/x-gzip"
                :show-file-list="false"
                :max-count="1">
                <template #upload-button>
                  <a-button
                    long
                    :disabled="fileList.length > 0 && !uploadError">
                    <i-icons-upload />点击上传</a-button
                  >
                </template>
              </a-upload>
              <div class="stop-row">
                <div
                  v-for="i in fileList"
                  :key="i"
                  class="flex flex-col w-full">
                  <div class="progress-row">
                    <div class="progress-name">
                      <i-icons-file />{{ i.name }}
                    </div>
                    <div class="progress-status">
                      <i-icons-failed v-if="uploadError" />
                      <template v-else>
                        <template v-if="successfulType">
                          <i-icons-success v-if="percentage === 100" />
                        </template>
                        <template v-if="resolving">
                          <i-icons-applying class="mr-1 rotate-infinite" />
                          <span class="text-3 text-xs leading-5"
                            >解析中...</span
                          >
                        </template>
                        <template v-else>
                          <!-- <i-icons-success v-if="percentage === 100" /> -->
                          <span v-if="percentage !== 100">{{
                            percentage + '%'
                          }}</span>
                        </template>
                      </template>
                    </div>
                  </div>
                  <span
                    v-if="uploadError"
                    class="text-danger text-xs leading-5">
                    {{ errorTipText }}
                  </span>
                  <a-progress
                    v-if="showProgress"
                    :percent="percentage / 100"
                    track-color="165DFF"
                    :show-text="false" />
                  <div class="flex-1"></div>
                </div>
                <span v-if="percentage !== 100 && percentage !== 0"
                  ><i-icons-delete-ash
                    color="#165dff"
                    class="cursor-pointer"
                    @click="handleDelete"
                /></span>
              </div>
            </div>
          </div>
        </a-form-item>
        <a-form-item label="版本号" field="dns_api_id" asterisk-position="end">
          <a-input
            v-model="formState.version"
            disabled
            :class="{ 'width-value-placeholder': formState.version }"
            placeholder="根据上传文件自动生成"></a-input>
        </a-form-item>

        <a-form-item label="版本说明" asterisk-position="end">
          <a-textarea
            v-model="formState.imprint"
            disabled
            :class="{ 'width-value-placeholder': formState.imprint }"
            placeholder="根据上传文件自动生成"
            :auto-size="{ maxRows: 5, minRows: 5 }"></a-textarea>
        </a-form-item>

        <!-- <a-form-item label="版本说明" asterisk-position="end">
          <div class="imprint-detail"><div v-html="markdownContent"></div></div>
        </a-form-item> -->
      </a-form>
    </a-spin>
  </CloudDialog>
</template>
<script lang="ts" setup>
import type { DomainItem } from '@/apis/model/resolve'
import { getAdminApiNodeVersionUploadParseApi } from '@/apis/modules/version'
// import { marked } from 'marked'
import { type FormInstance, type RequestOption } from '@arco-design/web-vue'
const emit = defineEmits(['reload'])
// import { v4 as uuidV4 } from 'uuid'
interface IProp {
  record?: DomainItem
}
// const markdownContent = ref('')
const fileList = ref<any[]>([])
const errorTipText = ref('上传失败，请重新上传')
const visible = defineModel<boolean>('visible', { required: true })
withDefaults(defineProps<IProp>(), {})
const formRef = ref<FormInstance>()
// const dnsNameOptions = ref<LabelValue[]>([])
const formState = ref({
  imprint: '',
  version: '',
  file_key: '',
  file: undefined,
  id: undefined
})
// 上传的文件
const loading = ref<boolean>(false)
const showProgress = computed(
  () => percentage.value !== 0 && percentage.value !== 100 && !uploadError.value
)
const baseUrl = computed(() => {
  return import.meta.env.VITE_BASE_URL
})

const {
  percentage,
  resolving,
  uploadError,
  initTus,
  startOrResumeUpload,
  pauseUpload
} = useUpload()
//上传组件
const customRequest = (option: RequestOption) => {
  const { fileItem } = option
  const file = fileItem.file!
  const isTarGz = file.type === 'application/x-gzip'
  if (!isTarGz) {
    fileList.value = []
    uploadError.value = true
    errorTipText.value = '只能上传 .tar.gz 格式的文件！'
    return false // 阻止上传
  }
  initTus({
    endpoint: baseUrl.value + 'admin/api/version',
    chunkSize: 5 * 1024 * 1024,
    file,
    type: 2,
    afterSuccess: getAnalysisState
  })
  startOrResumeUpload()
}

const beforeUpload = () => {
  successfulType.value = false
  resolving.value = false
  // 上传前的校验逻辑
  return true
}

const successfulType = ref(false)
let pollIntervalId

function getAnalysisState(data: string) {
  const id = data.substring(data.lastIndexOf('/') + 1)
  // loading.value = true
  resolving.value = true
  pollIntervalId = setInterval(getForAnalysisDetail, 1500, id)
  getForAnalysisDetail(id)
  // getDetail(data)
}

const getForAnalysisDetail = (id: string) => {
  //loading.value = true
  getAdminApiNodeVersionUploadParseApi({
    file_id: id
  }).then((res) => {
    //loading.value = false
    if (res.is_end) {
      stopPolling()
      if (res.error) {
        errorTipText.value = res.error
        uploadError.value = true
        resolving.value = false
        //ToastUtils.error(res.error)
      } else {
        //ToastUtils.success('上传成功')
        successfulType.value = true
        resolving.value = false
        formState.value.version = res.version ?? ''
        formState.value.imprint = res.imprint ?? ''
      }
    } else {
      //loading.value = true
    }
    return res
  })
}
const stopPolling = () => {
  if (pollIntervalId) {
    clearInterval(pollIntervalId)
  }
}
//获取版本号 版本说明等信息
// function getDetail(data: string) {
//   const id = data.substring(data.lastIndexOf('/') + 1)
//   loading.value = true
//   getAdminApiNodeVersionInfoDetailApi({
//     file_id: id
//   })
//     .then((res) => {
//       loading.value = false
//       formState.value.version = res.version ?? ''
//       formState.value.imprint = res.imprint ?? ''
//       resolving.value = false
//       //markdownContent.value = marked(res.imprint || '')
//     })

//     .finally(() => {
//       loading.value = false
//     })
// }

//const isUnClick = ref(true)

//清空表单
const resetField = () => {
  formRef.value?.resetFields()
  formState.value = {
    imprint: '',
    version: '',
    file_key: '',
    file: undefined,
    id: undefined
  }
  fileList.value = []
}

const handleClose = () => {
  pauseUpload()
  resetField()
  emit('reload')
  visible.value = false
}

onUnmounted(() => {
  clearInterval(pollIntervalId)
})

watchEffect(() => {
  if (!visible.value) {
    clearInterval(pollIntervalId)
    resolving.value = false
    successfulType.value = false
  }
})

const handleDelete = () => {
  pauseUpload()
  resetField()
  percentage.value = 0
}
</script>

<style scoped lang="less">
.stop-row {
  display: flex;
  padding: 4px;
  align-items: center;
  gap: 8px;
  align-self: stretch;
  width: 100%;
}
.progress-row {
  display: flex;
  padding: 4px;
  align-items: center;
  gap: 16px;
  align-self: stretch;
  .progress-name {
    display: flex;
    align-items: center;
    gap: 8px;
    flex: 1 0 0;
  }
  .progress-status {
    display: flex;
    align-items: center;
  }
}

.imprint-detail {
  display: flex;
  padding: 8px 12px;
  align-items: flex-start;
  gap: 6px;
  align-self: stretch;
  border-radius: 4px;
  border: 1px solid var(---color-border-4, #dfe2e5);
  background: var(---color-fill-1, #f7f8fa);
  height: 160px;
  overflow-x: hidden;
  overflow-y: auto;
  width: 100%;
}
</style>
